import { useState, useEffect } from "react";
import { DatePicker, message } from "antd";
import locale from "antd/lib/date-picker/locale/zh_CN";
import { getMenu } from "@/api/menu";
import Loading from "@/conpoments/loading";
import { getRelativeTime } from "@/utils/time";
import { getReport, generateReport } from "@/api/report";
import dayjs from "dayjs";
import "./index.less";

const dishZH_CN = ["早餐", "午餐", "晚餐", "宵夜"];

export default function StudentDetail(props: {
  studentId: string;
  schoolId: string;
  studentName: string;
}) {
  const { studentId, schoolId, studentName } = props;
  const [day, setDay] = useState(Date.now());
  const [menuData, setMenuData] = useState<any>({});
  const [report, setReport] = useState<any>(null);

  const [menuLoading, setMenuLoading] = useState(true);
  const [reportLoading, setReportLoading] = useState(true);

  const initReport = (studentId: string, menuId: string) => {
    setReportLoading(true);
    const reportList = JSON.parse(localStorage.getItem("report-list") || "[]");
    reportList.some((item: any) => {
      if (item.studentId === studentId && item.menuId === menuId) {
        setReport(item.report);
      }
      return false;
    });
    setReportLoading(false);
  };

  const getMenuData = async () => {
    setMenuLoading(true);
    try {
      const res: any = await getMenu(schoolId, dayjs(day).format("YYYY-MM-DD"));
      if (res?.statusCode !== 200) return;
      setMenuData(res.data);
      initReport(studentId, res.data.menuId);
    } catch (error) {
      message.error("获取菜单失败！");
    }
    setMenuLoading(false);
  };

  const checkReport = (taskId: string) => {
    const reportInterval = setInterval(async () => {
      try {
        const res: any = await getReport(taskId);
        console.log(res);

        if (res?.statusCode !== 200) {
          clearInterval(reportInterval);
          setReportLoading(false);
          return;
        }
        if (res.data.status === 2) {
          clearInterval(reportInterval);
          const reportList = JSON.parse(
            localStorage.getItem("report-list") || "[]"
          );
          reportList.push({
            studentId,
            menuId: menuData.menuId,
            report: res.data.report,
          });
          localStorage.setItem("report-list", JSON.stringify(reportList));
          setReport(res.data.report);
          setReportLoading(false);
        } else if (res.data.status === 3) {
          clearInterval(reportInterval);
          setReportLoading(false);
          message.error("生成报告失败，请稍后再试试把！");
        }
      } catch (error) {
        setReportLoading(false);
        clearInterval(reportInterval);
        message.error("生成数据报告是失败！");
        console.log(error);
      }
    }, 2000);
  };

  const handleGenerateReport = async () => {
    setReportLoading(true);
    try {
      const res: any = await generateReport({
        childUid: studentId,
        menuId: menuData.menuId,
      });

      if (res.statusCode !== 200) return;
      checkReport(res.data.taskId);
    } catch (error) {
      message.error("生成数据报告是失败！");
      console.log(error);
    }
  };

  const onDateChange = (date: any) => {
    setDay(date.valueOf());
  };

  useEffect(() => {
    setMenuData({});
    setReport(null);
    getMenuData();
  }, [day]);
  return (
    <div className="student-detail">
      <div className="date-picker">
        <DatePicker locale={locale} onChange={onDateChange} />
      </div>
      <div className="menu-container">
        <div className="menu-title">{`${studentName}${getRelativeTime(
          day
        )}菜谱${
          menuData.menuName ? "《" + menuData.menuName + "》" : ""
        }`}</div>

        {!menuLoading ? (
          menuData.dishList && menuData.menuId ? (
            Object.keys(menuData.dishList).map((dishKey, index) => {
              return (
                <div className="menu-item" key={index}>
                  <div className="menu-item-title">{dishZH_CN[index]}</div>
                  <div className="menu-item-box">
                    {menuData.dishList[dishKey].map((item: any) => {
                      return <div key={item.dishId}>{item.dishName}</div>;
                    })}
                  </div>
                </div>
              );
            })
          ) : (
            <div className="student-detail-no-data">
              <div>暂无数据...</div>
            </div>
          )
        ) : (
          <div className="student-detail-loading-container">
            <Loading />
          </div>
        )}
      </div>

      <div className="report-container">
        <div className="menu-title">数据报告</div>
        <div className="report-body">
          {!reportLoading ? (
            report ? (
              <div className="report-box">
                <div className="report-analysis">
                  <div className="report-analysis-card">{report.analysis}</div>
                </div>
                <div className="report-recommend-menu">
                  <div>推荐菜单：</div>
                  {report.menu.map((item: any, index: number) => {
                    return (
                      <div key={index}>
                        <span className="report-recommend-menu-name">
                          {item.name}
                        </span>
                        ：<span>{item.reason}</span>
                      </div>
                    );
                  })}
                </div>
              </div>
            ) : menuData.menuId ? (
              <div className="reporting-btn-box">
                <div onClick={handleGenerateReport}>生成报告</div>
              </div>
            ) : (
              <div className="student-detail-no-data">
                <div>暂无数据...</div>
              </div>
            )
          ) : (
            <Loading text="正在生成报告..."></Loading>
          )}
        </div>
      </div>
    </div>
  );
}
